const color = ['#00f0ff', '#0080ff', '#0050a0', '#002b4d', '#001f3f'];

// 初始化图表函数
function initChart(id, options) {
    const chartDom = document.getElementById(id);
    if (!chartDom) return;

    const chart = echarts.init(chartDom);
    chart.setOption({
        backgroundColor: 'transparent',
        color: color,
        ...options
    });

    // 监听窗口大小变化
    window.addEventListener('resize', () => chart.resize());
    return chart;
}

// 根据当前URL中的图表ID初始化对应图表
document.addEventListener('DOMContentLoaded', function() {
    const path = window.location.pathname;
    const chartId = path.split('/').pop() || 'trendChart';

    switch(chartId) {
        case 'trendChart':
            initChart('trendChart', {
                grid: { top: 30, bottom: 40, left: 60, right: 30 },
                xAxis: {
                    type: 'category',
                    data: data.tl,
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                series: [{
                    type: 'line',
                    smooth: true,
                    data: data.tv,
                    lineStyle: { color: color[0], width: 3 },
                    areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: color[0] }, { offset: 1, color: 'transparent' }] } },
                    itemStyle: { color: color[0], radius: 5 }
                }]
            });
            break;

        case 'categoryChart':
            initChart('categoryChart', {
                grid: { top: 30, bottom: 30, left: 180, right: 30 },
                xAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                yAxis: {
                    type: 'category',
                    data: data.cl.reverse(),
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                series: [{
                    type: 'bar',
                    data: data.cv.reverse(),
                    itemStyle: { color: color[1] },
                    label: {
                        show: true,
                        position: 'right',
                        color: '#fff',
                        fontSize: 12
                    }
                }]
            });
            break;

        case 'payChart':
            initChart('payChart', {
                grid: { top: 50, bottom: 30, left: 30, right: 30 },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['50%', '50%'],
                    data: data.pl.map((m, i) => ({ name: m, value: data.pa[i] })),
                    label: {
                        show: true,
                        formatter: '{b}: {d}%',
                        color: '#fff',
                        fontSize: 12
                    },
                    legend: {
                        orient: 'vertical',
                        left: 20,
                        top: 'center',
                        textStyle: { color: '#ccc', fontSize: 12 }
                    }
                }]
            });
            break;

        case 'demoChart':
            initChart('demoChart', {
                grid: { top: 50, bottom: 40, left: 60, right: 60 },
                xAxis: {
                    type: 'category',
                    data: data.al,
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                legend: {
                    data: ['Female', 'Male'],
                    textStyle: { color: '#ccc', fontSize: 12 },
                    right: 30,
                    top: 20
                },
                series: [
                    { name: 'Female', type: 'bar', data: data.fl, itemStyle: { color: color[2] } },
                    { name: 'Male', type: 'bar', data: data.ml, itemStyle: { color: color[3] } }
                ]
            });
            break;

        case 'heatChart':
            const categories = [...new Set(data.heatmap.map(d => d.category))];
            const demographics = [...new Set(data.heatmap.map(d => `${d.age_group}-${d.gender}`))];

            initChart('heatChart', {
                grid: { top: 50, bottom: 80, left: 150, right: 50 },
                xAxis: {
                    type: 'category',
                    data: categories,
                    axisLabel: { color: '#ccc', fontSize: 11, rotate: 45 }
                },
                yAxis: {
                    type: 'category',
                    data: demographics,
                    axisLabel: { color: '#ccc', fontSize: 11 }
                },
                visualMap: {
                    min: 0,
                    max: Math.max(...data.heatmap.map(d => d.count)),
                    orient: 'horizontal',
                    left: 'center',
                    bottom: 20,
                    textStyle: { color: '#ccc', fontSize: 11 }
                },
                series: [{
                    type: 'heatmap',
                    data: data.heatmap.map(d => [
                        categories.indexOf(d.category),
                        demographics.indexOf(`${d.age_group}-${d.gender}`),
                        d.count
                    ]),
                    label: { show: true, fontSize: 10, color: '#fff' }
                }]
            });
            break;

        case 'catAvgChart':
            initChart('catAvgChart', {
                grid: { top: 30, bottom: 30, left: 180, right: 30 },
                xAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12, formatter: '¥{value}' }
                },
                yAxis: {
                    type: 'category',
                    data: data.cal.reverse(),
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                series: [{
                    type: 'bar',
                    data: data.cav.reverse(),
                    itemStyle: { color: color[2] },
                    label: {
                        show: true,
                        position: 'right',
                        color: '#fff',
                        fontSize: 12,
                        formatter: '¥{value}'
                    }
                }]
            });
            break;

        case 'avgPriceChart':
            initChart('avgPriceChart', {
                grid: { top: 30, bottom: 30, left: 180, right: 30 },
                xAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12, formatter: '¥{value}' }
                },
                yAxis: {
                    type: 'category',
                    data: data.pl,
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                series: [{
                    type: 'bar',
                    data: data.pl.map((_, i) => (data.pa[i] / data.pv[i]).toFixed(2)),
                    itemStyle: { color: color[0] },
                    label: {
                        show: true,
                        position: 'right',
                        color: '#fff',
                        fontSize: 12,
                        formatter: '¥{value}'
                    }
                }]
            });
            break;

        case 'predictionChart':
            initChart('predictionChart', {
                grid: { top: 50, bottom: 80, left: 60, right: 60 },
                legend: {
                    data: ['实际值', 'XGBoost预测', '随机森林预测', 'GBR预测'],
                    textStyle: { color: '#ccc', fontSize: 12 },
                    top: 20
                },
                xAxis: {
                    type: 'category',
                    data: data.predictions.map(d => d.date),
                    axisLabel: {
                        color: '#ccc',
                        fontSize: 10,
                        rotate: 45,
                        interval: Math.ceil(data.predictions.length / 5) // 只显示部分标签避免拥挤
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                series: [
                    { name: '实际值', type: 'line', data: data.predictions.map(d => d.actual), lineStyle: { width: 2 } },
                    { name: 'XGBoost预测', type: 'line', data: data.predictions.map(d => d.xgb_pred), lineStyle: { width: 2, type: 'dashed' } },
                    { name: '随机森林预测', type: 'line', data: data.predictions.map(d => d.rf_pred), lineStyle: { width: 2, type: 'dashed' } },
                    { name: 'GBR预测', type: 'line', data: data.predictions.map(d => d.gbr_pred), lineStyle: { width: 2, type: 'dashed' } }
                ]
            });
            break;

        case 'featureImportanceChart':
            const features = Object.keys(data.feature_importance.xgb);
            initChart('featureImportanceChart', {
                grid: { top: 50, bottom: 120, left: 200, right: 60 },
                legend: {
                    data: ['XGBoost', '随机森林', 'GBR'],
                    textStyle: { color: '#ccc', fontSize: 12 },
                    top: 20
                },
                xAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12 },
                    name: '重要性分数',
                    nameTextStyle: { color: '#ccc', fontSize: 12 }
                },
                yAxis: {
                    type: 'category',
                    data: features,
                    axisLabel: {
                        color: '#ccc',
                        fontSize: 11,
                        formatter: function(value) {
                            return value.length > 15 ? value.substring(0, 15) + '...' : value;
                        }
                    }
                },
                series: [
                    { name: 'XGBoost', type: 'bar', data: Object.values(data.feature_importance.xgb) },
                    { name: '随机森林', type: 'bar', data: Object.values(data.feature_importance.rf) },
                    { name: 'GBR', type: 'bar', data: Object.values(data.feature_importance.gbr) }
                ]
            });
            break;

        case 'segmentPredictionChart':
            initChart('segmentPredictionChart', {
                grid: { top: 50, bottom: 100, left: 250, right: 60 },
                legend: {
                    data: ['实际值', '预测值'],
                    textStyle: { color: '#ccc', fontSize: 12 },
                    top: 20
                },
                xAxis: {
                    type: 'value',
                    axisLabel: { color: '#ccc', fontSize: 12 }
                },
                yAxis: {
                    type: 'category',
                    data: data.segment_predictions.map(d => `${d.gender}-${d.age_group}-${d.category}`),
                    axisLabel: {
                        color: '#ccc',
                        fontSize: 10,
                        formatter: function(value) {
                            const parts = value.split('-');
                            return `${parts[0]}-${parts[1]}\n${parts[2]}`;
                        }
                    }
                },
                series: [
                    { name: '实际值', type: 'bar', data: data.segment_predictions.map(d => d.actual) },
                    { name: '预测值', type: 'bar', data: data.segment_predictions.map(d => d.pred_sk) }
                ]
            });
            break;
    }
});